# -*- coding: utf-8 -*-

"""
    This file is part of Free Herbarium.

    Free Herbarium is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Free Herbarium is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Free Herbarium.  If not, see <http://www.gnu.org/licenses/>.
"""

class UnrecognisedArgumentError:
      """ The name of a given species is not given. It must be."""
      def __init__(self, value):
          self.value = value
          
      def __str__(self):
          return repr(self.value)

class OutofplaceError:
      """ The name of a given species is not given. It must be."""
      def __init__(self, value):
          self.value = value
          
      def __str__(self):
          return repr(self.value)

class Preprocessor:
  
      def __init__(self, lines):
          self.lines = lines
          
      def _define(self, key, val):
          with open("tmp/definitions","a") as f:
               f.write(key+"="+val+"\n")
          
      def _addLatin(self, lang, equiv):
          with open("tmp/lat_%s" % lang, "a") as f:
               sp = equiv.split("=")
               f.write(sp[0]+"=u'"+sp[1]+"'\n")
          
      def save(self):
          family = False
          for line in self.lines:
              action = line.split(" ")[0]
              args = line.split(" ")[1:]
              if action == "set":
                 self._define(args[0],args[1])
              elif action == "begin":
                 if args[0] == "families":
                    family = True # begin listening
                 else:
                    raise UnrecognisedArgumentError("Argument %s for function 'begin'" % args[0])
              elif action == "end":
                 if args[0] == "families":
                    family = False # stop listening
                 else:
                    raise UnrecognisedArgumentError("Argument %s for function 'begin'" % args[0])
              elif action == "lat":
                 if family == True:
                    self._addLatin(args[0],args[1])
                 else:
                    raise OutofplaceError("'lat' function must be placed inside a 'family' block.")